package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"logi-flow/cache"
	"logi-flow/moder"
	"strconv"
	"time"
)

func PerAdd(c *gin.Context) {
	per_name := c.PostForm("per_name")
	per_yeas, _ := strconv.Atoi(c.PostForm("per_yeas"))
	data := moder.Per{
		//Model:   gorm.Model{},
		PerName: per_name,
		PerYeas: per_yeas,
	}
	moder.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
}
func OrderAdd(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_name := c.PostForm("order_name")
	pid, _ := strconv.Atoi(c.PostForm("pid"))
	data := moder.Order{
		//Model:     gorm.Model{},
		OrderCode: order_code,
		OrderName: order_name,
		Pid:       pid,
	}
	moder.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
}
func OrderList(c *gin.Context) {
	var Orders []moder.Order

	redis_key := "orders_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		moder.DB.Debug().Find(&Orders)
		jsonData, _ := json.Marshal(&Orders)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &Orders)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": Orders,
	})
}
func PerOrderDetail(c *gin.Context) {
	pid := c.Query("pid")
	/*
		SELECT
		  *
		FROM
		  pers
		  LEFT JOIN orders ON pers.id = orders.pid
		WHERE
		  orders.pid = 1
	*/
	var perOrder moder.PerOrder
	redis_key := "pers_list_" + pid
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		moder.DB.Table("orders").Select(
			"orders.order_code AS OrderCode",
			"orders.id as  OrderId",
			"orders.order_name AS OrderName",
			"pers.per_name AS PerName",
			"pers.per_yeas AS PerYeas").
			Joins(" LEFT JOIN pers ON pers.id = orders.pid").
			Where(" orders.pid = ?", pid).Debug().Find(&perOrder)
		jsonData, _ := json.Marshal(&perOrder)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Second*10)
	} else {
		json.Unmarshal([]byte(cacheData), &perOrder)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": perOrder,
	})
}
